﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SaiLing.SingleSignOn.Application.Service.Interfaces.System;
using SaiLing.Common;
using SaiLing.SingleSignOn.Application.Core.DataTransferObject.System;
using SaiLing.SingleSignOn.Application.Service;
using SaiLing.SingleSignOn.Domain.Entities.System;
using SaiLing.SingleSignOn.Application.Core.Controllers;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using SaiLing.SingleSignOn.Application.Core.Params;

namespace SaiLing.SingleSignOn.WebApi.Controllers
{
    public class AccountController : BaseController
    {
        private IAccountService AccountService { get; set; }

        public AccountController(IAccountService accountService)
        {
            this.AccountService = accountService;
        }

        [AllowAnonymous]
        [HttpPost]
        public Task<ApiJsonResultData> Login([FromBody]AccountLoginModel model) => new ApiJsonResultData().RunWithTryAsync(async x =>
        {
            var user = await AccountService.SignIn(model.UserName, model.Password);
            var identity = new ClaimsIdentity("bob");
            identity.AddClaim(new Claim(ClaimTypes.UserData,
                JsonConvert.SerializeObject(new { id = user.Id, password = user.Password })));
            var principal = new ClaimsPrincipal(identity);
            await Web.HttpContext.Current.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
            //var token = UserCacheHelper.SaveCache(user, model.RememberMe);
            //HttpContext.Current.Session["Token"] = token;
            var log = ServiceFactory.GetService<IOperationLogService>();//.Log("管理员登录", $"登录帐号:{user.LoginName},登陆时间:{DateTime.Now}", new LogUser { Id = user.Id, LogType = Domain.Enums.System.LogType.Administrator, UserName = user.LoginName });
            //x.Data = token;
            x.RedirectUrl = model.Return;
        });
        [HttpGet]
        public Task<ApiJsonResultData> Init()
        {
            return new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var user = new Account
                {
                    LoginName = "admin",
                    Email = "287564883@qq.com",
                    IsAdministrator = true,
                    IsApproved = true,
                    PasswordSalt = StringExtensions.GenerateSalt()
                };
                user.Password = "123456".EncryptPassword(user.PasswordSalt);
                await AccountService.Add(user);
                await AccountService.SaveChangesAsync();
            });
        }

        [HttpGet]
        public async Task<ApiJsonResultData> GetByKey(Guid id)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                x.Data = await AccountService.GetByKey(id);
            });
        }

        [HttpGet]
        public async Task<ApiJsonResultData> List(string name)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var list = await AccountService.List(name);
                x.Data = list;
            });
        }

        [HttpGet]
        public async Task<ApiJsonResultData> PageList(int pageIndex, int pageSize, string name)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var list = await AccountService.PageList(pageIndex, pageSize, name);
                x.Data = list;
            });
        }

        public async Task<ApiJsonResultData> Create([FromForm]Account model, string @return)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                if (model.Positions != null)
                    model.Positions.ForEach(f => { f.AccountId = LogUser.Id; });

                await AccountService.Create(model, LogUser);
                x.AddMessage("创建成功");
                x.RedirectUrl = @return;
            });
        }

        public async Task<ApiJsonResultData> Edit([FromForm]Account model, string @return)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                if (model.Positions != null)
                    model.Positions.ForEach(f => { f.AccountId = LogUser.Id; });

                await AccountService.Edit(model, LogUser);
                x.AddMessage("修改成功");
                x.RedirectUrl = @return;
            });
        }

        [HttpPost]
        public async Task<ApiJsonResultData> EditPassword([FromForm]Account model, string @return)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                await AccountService.EditPassword(model, LogUser);
                x.AddMessage("修改成功");
                x.RedirectUrl = @return;
            });
        }

        [HttpPost]
        public async Task<ApiJsonResultData> EditLockUnLock([FromBody]List<RemoveParam> model,bool islock)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                if (model != null && model.Any())
                {
                    model.ToList().ForEach(f =>
                    {
                        var act = new Account { Id = f.Id };

                        if (islock)
                        {
                            AccountService.EditLock(act, LogUser);
                        }
                        else {
                            AccountService.EditUnLock(act, LogUser);
                        }

                    });
                    
                    x.ReloadPage = true;
                    x.AddMessage("修改成功");
                }
                else
                    x.AddErrorMessage("至少选择一条数据");
            });
        }

        [HttpPost]
        public async Task<ApiJsonResultData> Delete([FromBody]List<RemoveParam> model)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                if (model != null && model.Any())
                {
                    var list = new List<Account>();
                    model.ToList().ForEach(f =>
                    {
                        list.Add(new Account { Id = f.Id });
                    });
                    await AccountService.Delete(list.ToArray(), LogUser);
                    x.ReloadPage = true;
                    x.AddMessage("删除成功");
                }
                else
                    x.AddErrorMessage("至少选择一条数据");
            });
        }

    }
}